import React, { Component } from 'react';
import {
    StyleSheet, Image, TouchableOpacity, Text
} from "react-native";
import { GLOBAL } from '../../../config/global';
import { API, API_GENERATE } from '../../../config/api';
import HTTP from '../../../utils/http';
import StorageHelper from '../../../utils/storageHelper';
import { STORAGE_CONSTANT } from '../../../config/storage';
import Upload from '../../../utils/Upload';
import JsonUtils from '../../../utils/JsonUtils';
import ToastUtil from '../../../utils/toast';
import navigationSeevice from '../../../components/navigation/navigationSeevice';


const scale = GLOBAL.SCALE;
const defaultImg = require('../../../imgs/user-head.png');
export class UserHeadCpt extends Component {
    constructor(props) {
        super(props);
        this.state = {
            headImg: defaultImg,// 初始化头像
            navBaropacity: 0
        }
        //图片选择器参数设置
        this.imgOptions = {
            title: '请选择图片来源',
            cancelButtonTitle: '取消',
            takePhotoButtonTitle: '拍照',
            chooseFromLibraryButtonTitle: '相册图片',
            quality: 0.1,
            storageOptions: {
                skipBackup: true,
                path: 'images'
            }
        };
    }
    componentWillMount () {
        this._init();
    }
    async componentWillReceiveProps (props) {
        if (!props) return;
        this._init();
    }

    _init = async () => {
        await this._userInfo();
        this._getHead();
    }

    // 获取用户基本信息
    _userInfo = async () => {
        let account = null;
        try {
            account = await StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY);
        } catch (error) {
            console.log(error);
        }
        this.userInfo = JSON.parse(account) || {};
    }

    //获取头像
    _getHead = async () => {
        let { avatar, avatarUrl } = this.userInfo || {};
        // 获取头像接口
        if (avatarUrl) {
            this.setState({
                headImg: { uri: avatarUrl }
            })
        } else if (avatar) {
            if (this.orderly) return;
            this.orderly = true;
            let headObj = await HTTP.GET(API_GENERATE(API.GET_IMG_VIEW), { fileId: avatar }, {
                rejectError: false, //是否将错误数据以reject的方式返回
                handerError: true //统一出错处理 通过toast提示
            }, 30000);
            this.orderly = false;
            this.userInfo.avatarUrl = headObj.image;
            StorageHelper.set(STORAGE_CONSTANT.USER_INFO_KEY, this.userInfo);
            if (headObj) {
                this.setState({
                    headImg: { uri: headObj.image }
                })
            } else {
                this.setState({
                    ls: true
                })
            }
        } else {
            this.setState({
                ls: true
            })
        }
    }


    //点击头像 更改
    _changeLog = () => {
        navigationSeevice.navigate('UserInfo', this.userInfo)
    }

    //头像上传图片
    _uploadImg = async (imgUrl) => {
        let uploadImgObj = {
            imgUrl,
            url: API_GENERATE(API.IMG_UPLOAD),
        }
        let responseData = await Upload.uploadImg(uploadImgObj);
        if (responseData) {
            this.setState({
                headImg: { uri: responseData.filePath }
            })
            this._changeImg(responseData.fileId, responseData.filePath);
        }
    }

    // 图片修改
    _changeImg = async (fileId, imgUrl) => {
        const requestObj = {};
        requestObj.fileId = fileId;
        let resultObj = await HTTP.POST(API_GENERATE(API.CHANGE_LOG), requestObj);
        if (resultObj) {
            StorageHelper.get(STORAGE_CONSTANT.USER_INFO_KEY).then((res) => {
                let resData = JsonUtils.stringToJson(res);
                resData.avatarUrl = imgUrl;
                resData.avatar = fileId;
                StorageHelper.set(STORAGE_CONSTANT.USER_INFO_KEY, JsonUtils.jsonToString(resData));
            })
        }
        ToastUtil.showSuccess(resultObj);
    }



    render () {
        let { headImg } = this.state;
        let { data } = this.props;
        let { stylesHeadImgBox, stylesHeadImg } = data || {};
        return (
            <TouchableOpacity style={[styles.headImgBox, stylesHeadImgBox || null]} onPress={this._changeLog} activeOpacity={1}>
                <Image style={[styles.headImg, stylesHeadImg || null]} source={headImg} />
            </TouchableOpacity>
        )
    }
}
const styles = StyleSheet.create({
    headImgBox: {
        width: 28 * scale,
        height: 28 * scale,
    },
    headImg: {
        width: 28 * scale,
        height: 28 * scale,
        borderRadius: 14 * scale
    }
})